<script>
import { computed, defineComponent, inject, reactive, ref, toRaw } from 'vue'
import { libFileList, libNewFolder, libDel } from '@Config/server/api'
import DataTable from '@Components/dataTable'
import { createPagination, Messages, uploadParams } from '@Config/config'
import { message, Modal } from 'ant-design-vue'
import MakeForm, { MakeFormState } from '@Components/makeForm'
import ColorBlock from '@Components/colorBlock'
import { useUrl, transform_pre_fn } from '@Hooks/url'
import { useRoute } from 'vue-router'
import FolderList from '@Components/folderList'
import { fileType, fileTypeDataStaus } from '@Config/const'
import { cloneDeep, findIndex, uniqueId } from 'lodash'
import { useStore } from 'vuex'
import useBreadcrumb from '@Hooks/breadcrumb'
import * as Antd from 'ant-design-vue'
import { confirm } from '@Config/config'
import { IconShanChu, IconHuFu } from '@Assets/fonts/svg'
import { fileApi } from '@Hooks/fileApi'
import Tips from '@Components/tips'

export default defineComponent({
  components: {
    DataTable,
    MakeForm,
    ColorBlock,
    FolderList,
  },
  setup(props, context) {
    let {
      removeFile,
      recoveryFile,
      batchRecoveryFile,
      batchReoveFile,
    } = fileApi()
    let form_config = [
      {
        key: 'fileType',
        initValue: null,
        ignore: true,
        // uiType: 'select',
        // source: fileType(),
        // col: { span: 6 },
        // formItem: { label: '文件类型' },
        // attr: { placeholder: '文件类型' },
      },
      {
        key: 'dataStatus',
        initValue: -1,
        ignore: true,

        // uiType: 'select',
        // source: fileTypeDataStaus(),
        // col: { span: 6 },
        // formItem: { label: '文件类型' },
        //  attr: { placeholder: '文件类型' },
      },
      {
        key: 'id',
        initValue: 0,
        ignore: true,

        // uiType: 'select',
        // // source: TYPE_LIST(),
        // col: { span: 6 },
        // formItem: { label: 'id' },
        // attr: { placeholder: 'id' },
      },
    ]

    let form_state = reactive({ data: MakeFormState(form_config) })

    //表格数据配置
    let tableData = reactive({
      data: {
        source: [],
        columns: [
          {
            key: 'yyyyMmDd',
            dataIndex: 'yyyyMmDd',
            title: '',
          },
        ],
      },
    })

    //表格loading状态
    let loading = reactive({ search_loading: false, delete_loading: false })

    let resetHandler = () => {
      form_ref.value.resetState()
      pagination.data.current = 1
      searchData()
    }
    //查询按钮监听
    let searchHandler = () => {
      pagination.data.current = 1
      searchData()
    }
    let route = useRoute()

    let { fromStateToQuery } = useUrl({
      fn: async () => {
        loading.search_loading = true
        let _params = {
          ...form_state.data,
          index: pagination.data.current,
          size: pagination.data.pageSize,
        }
        let _result = await libFileList(_params)
        if (_result.code != 0) {
          Messages.add(message.error('查询失败' + _result.msg))
          return
        }
        pagination.data.pageSize = _result.data?.size
        pagination.data.current = _result.data?.index
        pagination.data.total = _result.data?.total
        tableData.data.source = _result.data?.records
        loading.search_loading = false
      },
      formState: [
        {
          key: 'id',
          fn: transform_pre_fn['fn.number0'],
          default: 0,
        },
        {
          key: 'fileType',
          fn: transform_pre_fn['fn.number0'],
          default: null,
        },
        {
          key: 'dataStatus',
          fn: transform_pre_fn['fn.number0'],
          default: -1,
        },
      ],
    })
    //查询数据
    let searchData = async () => {
      fromStateToQuery({ path: route.path })
    }

    //表格分页
    let pagination = reactive({
      data: createPagination(searchData, true, false),
    })

    //分页点击
    // pagination.data.onChange = (pageNumber, pageSize) => {
    //   pagination.data.current = pageNumber
    //   pagination.data.pageSize = pageSize
    //   searchData()
    // }
    //ref dom
    let form_ref = ref(null)
    //新增公告回调函数

    //默认查询
    //searchData()

    let selectHandler = (e) => {
      //searchHandler()
      form_state.data.id = e.target.id
      tableData.data.source.map((x) => {
        if (x.id == e.target.id) {
          x.local_loading = true
        }
      })
      fromStateToQuery({ path: route.path })
    }

    //注册右上角的菜单
    let rightMenu = inject('rightIconMenu')
    rightMenu.data = null

    //监听 文件夹、文件是否选中
    let checkBoxHandler = (e) => {
      let _index = findIndex(tableData.data.source, { id: e.target.id })
      tableData.data.source[_index].selected = e.e.target.checked
    }

    //选择/取消 全部
    let selectAllHandler = (e) => {
      tableData.data.source.map((x) => {
        x.selected = e.target.checked
      })
    }

    let tables_selected = computed(() => {
      return tableData.data.source.filter((x) => x.selected)
    })

    let operList = () => {
      return [
        {
          label: '批量取消分享',
          action: () => batchRecoveryFile(tables_selected.value),
          icon: <IconHuFu />,
        },
        // {
        //   label: '删除',
        //   action: batchReoveFile,
        //   icon: <IconShanChu />,
        //   attr: {
        //     danger: true,
        //   },
        // },
      ]
    }

    let rightMenuHandler = (e) => {
      if (!e.rightMenu) {
        e.rightMenu = (
          <Antd.Menu selectedKeys={[]}>
            {operList()?.map((x) => {
              return (
                <Antd.MenuItem>
                  <Antd.Button
                    type="link"
                    onClick={x.action}
                    size="small"
                    disabled={tables_selected.value.length == 0}
                  >
                    {x.label}
                  </Antd.Button>
                </Antd.MenuItem>
              )
            })}
          </Antd.Menu>
        )
      }
    }

    let folder_right_menu_fn = () => {
      return () => {
        return [
          {
            label: '删除',
            action: removeFile,
          },
          {
            label: '取消分享',
            action: recoveryFile,
          },
        ]
      }
    }
    return {
      tableData,
      loading,
      pagination,
      form_config,
      form_state,
      form_ref,
      selectHandler,
      checkBoxHandler,
      selectAllHandler,
      tables_selected,
      rightMenuHandler,
      operList,
      folder_right_menu_fn,
    }
  },
  render() {
    //     onRecovery={this.recoveryHandler}
    //                onRemove={this.removeHandler}
    // onMoveTrash={this.moveTrashHandler}

    return (
      <a-row gutter={[20, 20]} onContextmenu={this.rightMenuHandler}>
        <a-col span={24}>
          <Tips
            list={this.tableData.data.source}
            selected={this.tables_selected}
          >
            <a-space>
              {this.operList().map((x) => {
                return (
                  <a-button
                    type="primary"
                    onClick={x.action}
                    disabled={this.tables_selected.length == 0}
                    title={x.label}
                    {...x.attr}
                    shape="circle"
                  >
                    {x.icon}
                  </a-button>
                )
              })}

              <a-checkbox onChange={this.selectAllHandler}>全选</a-checkbox>
            </a-space>
          </Tips>
        </a-col>
        <a-col span={24} class="vh69">
          <FolderList
            list={cloneDeep([...this.tableData.data.source])}
            onSelect={this.selectHandler}
            onCheckBox={this.checkBoxHandler}
            role="trash"
            rightMenuFn={this.folder_right_menu_fn()}
          />
          <a-affix {...this.pagination_affix_attr()}>
            <div class="affix">
              <a-pagination {...this.pagination.data} />
            </div>
          </a-affix>
        </a-col>
      </a-row>
    )
  },
})
</script>
